package cn.zebra.dev.admin.module.admin.controller;

import cn.zebra.dev.admin.module.admin.dto.AdminDTO;
import cn.zebra.dev.admin.module.admin.dto.AdminListDTO;
import cn.zebra.dev.admin.module.admin.entity.AdminEntity;
import cn.zebra.dev.admin.module.admin.service.AdminService;
import cn.zebra.dev.admin.module.admin.vo.AdminListQueryVO;
import cn.zebra.dev.admin.module.admin.vo.AdminUpdatePasswordVO;
import cn.zebra.dev.admin.module.login.SecurityAdminService;
import cn.zebra.dev.base.module.admin.entity.BaseAdmin;
import cn.zebra.dev.common.constant.ParamsConstant;
import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.common.utils.DateUtils;
import cn.zebra.dev.common.utils.ObjectUtils;
import cn.zebra.dev.common.utils.SecurityUtils;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author runnable@sina.cn
 */
@RestController
@Api(tags = "后台用户管理")
@RequestMapping("/user")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private SecurityAdminService securityService;

    @GetMapping("/list")
    @ApiOperation("用户管理")
    public Result<PageUtils<AdminListDTO>> list(
            AdminListQueryVO vo,
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page) {
        BaseAdmin baseAdmin = securityService.getBaseAdmin();
        Map<String, Object> params = ObjectUtils.objectConvertMap(vo);
        if (!baseAdmin.getRoleIds().contains(1L)) {
            params.put("createId", baseAdmin.getId());
        }
        params.put(ParamsConstant.LIMIT, limit);
        params.put(ParamsConstant.PAGE, page);
        PageUtils<AdminEntity> queryPage = adminService.findPage(params);
        PageUtils<AdminListDTO> data = new PageUtils<>();
        List<AdminEntity> list = queryPage.getList();
        if (list.size() > 0) {
            List<AdminListDTO> dtoList = new LinkedList<>();
            list.forEach(entity -> {
                AdminListDTO dto = new AdminListDTO();
                BeanUtils.copyProperties(entity, dto);
                dto.setLastLoginTime(DateUtils.convertTimeStampToLocalDateTime(entity.getLastLoginTime()));
                dtoList.add(dto);
            });
            data.setList(dtoList);
        }
        return Result.success(data);
    }

    @PostMapping("/updatePassword")
    @ApiOperation("修改密码")
    public Result updatePassword(@Valid @RequestBody AdminUpdatePasswordVO vo) {
        String oldPassword = vo.getOldPassword();
        BaseAdmin admin = securityService.getBaseAdmin();
        String salt = admin.getSalt();
        if (!SecurityUtils.getMd5(salt + admin.getLastLoginTime() + oldPassword).equals(admin.getPassword())) {
            return Result.error("原密码错误!");
        }
        String newPassword = vo.getNewPassword();
        if (newPassword.equals(oldPassword)) {
            return Result.error("旧密码与新密码一致!");
        }
        if (!adminService.resetPassword(admin.getId(), salt, newPassword)) {
            throw new RuntimeException("修改失败!");
        }
        return Result.success("修改成功!");
    }

    @GetMapping("/get/{id}")
    @ApiOperation("获取用户信息")
    public Result<AdminDTO> get(@PathVariable Long id) {
        AdminEntity entity = adminService.findById(id);
        AdminDTO data = new AdminDTO();
        BeanUtils.copyProperties(entity, data);
        data.setLastLoginTime(DateUtils.convertTimeStampToLocalDateTime(entity.getLastLoginTime()));
        return Result.success(data);
    }

    @PostMapping("/save")
    @ApiOperation("保存用户")
    public Result save(@Valid @RequestBody AdminEntity entity) {
        adminService.saveAdmin(entity, 1L);
        return Result.success("添加成功!");
    }

    @PostMapping("/update/{id}")
    @ApiOperation("修改用户")
    public Result save(@PathVariable Long id, @Valid @RequestBody AdminEntity entity) {
        adminService.updateAdmin(id, entity, 1L);
        return Result.success("添加成功!");
    }

    @GetMapping("/delete/{id}")
    @ApiOperation("删除用户")
    public Result delete(@PathVariable Long id) {
        if (adminService.deleteAdmin(id)) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败!");
    }
}
